package com.sumfun.blog.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sumfun.blog.common.BaseResponse;
import com.sumfun.blog.common.ErrorCode;
import com.sumfun.blog.common.ResultUtils;
import com.sumfun.blog.exception.BusinessException;
import com.sumfun.blog.model.domain.Websitetool;
import com.sumfun.blog.service.WebsitetoolService;
import com.sumfun.blog.mapper.WebsitetoolMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 17337
 * @description 针对表【websitetool】的数据库操作Service实现
 * @createDate 2025-02-06 15:46:36
 */
@Service
public class WebsitetoolServiceImpl extends ServiceImpl<WebsitetoolMapper, Websitetool>
        implements WebsitetoolService {


    public Map<String, String> getWebsiteInfoByUrl(String url) throws IOException {
        /*使用Jsoup库的connect方法连接到指定的URL，并使用get方法获取网页的内容。它返回一个Document对象，表示整个HTML文档。*/
        Document doc = Jsoup.connect(url).get();
        /*获取网站元数据*/
        String title = doc.title();
        Element descriptionTag = doc.select("meta[name=description]").first();
        String description = descriptionTag != null ? descriptionTag.attr("content") : "";
        Element iconTag = doc.select("link[rel=icon], link[rel=shortcut icon]").first();
        String iconLink = iconTag != null ? iconTag.attr("href") : "";

        /*返回前端*/
        Map<String, String> map = new HashMap<>();
        map.put("title", title);
        map.put("description", description);
        map.put("iconLink", iconLink);
        return map;
    }

    @Override
    public boolean addWebsitetool(String url, String name, String classes) {
        if (url == null || name == null || classes == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        try {
            Map<String, String> infoByUrl = getWebsiteInfoByUrl(url);
            Websitetool websitetool = new Websitetool();
            websitetool.setName(name);
            websitetool.setClasses(classes);
            websitetool.setUrl(url);

            websitetool.setIconLink(infoByUrl.get("iconLink"));
            websitetool.setTitle(infoByUrl.get("title"));
            websitetool.setDescription(infoByUrl.get("description"));
            boolean save = this.save(websitetool);
            return save;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean updateWebsitetool(Long id, String url, String name, String classes) {
        try {
            if (id == null || url == null || name == null || classes == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
            Websitetool websitetoolOld = this.getById(id);
            if (websitetoolOld == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
            Map<String, String> infoByUrl = null;
            infoByUrl = getWebsiteInfoByUrl(url);
            websitetoolOld.setName(name);
            websitetoolOld.setUrl(url);
            websitetoolOld.setClasses(classes);

            websitetoolOld.setTitle(infoByUrl.get("title"));
            websitetoolOld.setIconLink(infoByUrl.get("iconLink"));
            websitetoolOld.setDescription(infoByUrl.get("description"));
            boolean save = this.updateById(websitetoolOld);
            return save;
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }

    @Override
    public ArrayList getClassesList() {
        ArrayList<Map<String, Object>> result = new ArrayList<>();


        List<Websitetool> websitetoolList = this.list();

        // 用于存储具有相同classes的工具的临时列表
        Map<String, List<Map<String, Object>>> classifiedTools = new HashMap<>();

        for (Websitetool tool : websitetoolList) {
            // 创建一个Map来存储单个工具的数据
            Map<String, Object> toolData = new HashMap<>();
            toolData.put("id", tool.getId());
            toolData.put("name", tool.getName());
            toolData.put("title", tool.getTitle());
            toolData.put("classes", tool.getClasses());
            toolData.put("url", tool.getUrl());
            toolData.put("iconLink", tool.getIconLink());
            toolData.put("description", tool.getDescription());
            toolData.put("visitCount", tool.getVisitCount());

            // 根据classes将工具分类
            String classes = tool.getClasses();
            classifiedTools.computeIfAbsent(classes, k -> new ArrayList<>()).add(toolData);
        }

        // 构建最终的结果列表
        for (Map.Entry<String, List<Map<String, Object>>> entry : classifiedTools.entrySet()) {
            Map<String, Object> outerMap = new HashMap<>();
            outerMap.put("classes", entry.getKey());
            outerMap.put("dataArr", entry.getValue());
            result.add(outerMap);
        }

        // 注意：这里假设你想要的结果是按照classes分类的列表。
        // 如果你的需求有所不同（比如不分类，只返回一个扁平的列表），你需要调整这里的逻辑。

        return result;
    }
}




